package middleware

import (
	"context"
	"time"

	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/go-kratos/kratos/v2/transport/http"

	"gitee.com/snitso/micro/app/evaluation/internal/conf"
	"gitee.com/snitso/micro/pkg/sessions"
)

func SessionStore(app *conf.App, s *sessions.RedisStore) middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
			if tr, ok := transport.FromServerContext(ctx); ok {
				if ht, ok := tr.(*http.Transport); ok {
					session, err := s.Get(ht, "session")
					session.Values["timestamp"] = time.Now().Unix()
					if err = session.Save(ht); err != nil {
						panic(err)
					}

					ctx = context.WithValue(ctx, "env", app.Env)
					ctx = context.WithValue(ctx, "session", session)
				}
			}
			return handler(ctx, req)
		}
	}
}
